package com.huaxin.common.media;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseFragment;
import com.huaxin.common.R;
import com.huaxin.common.cache.DiskCache;
import com.huaxin.common.media.adapter.BaseRecyclerAdapter;
import com.huaxin.common.media.adapter.ImageAdapter;
import com.huaxin.common.media.adapter.ImageFolderAdapter;
import com.huaxin.common.media.bean.Image;
import com.huaxin.common.media.bean.ImageFolder;
import com.huaxin.common.media.config.ImageLoaderListener;
import com.huaxin.common.media.contract.SelectImageContract;

import net.qiujuer.genius.ui.Ui;
import net.qiujuer.genius.ui.widget.Button;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


/**
 * 图片选择库实现界面
 */
public class SelectFragment extends BaseFragment implements  View.OnClickListener,
        ImageLoaderListener, BaseRecyclerAdapter.OnItemClickListener ,
        MediaStoreDataFactory.PictureSourceCallback, MediaStoreDataFactory.FolderSourceCallback {
    RecyclerView mContentView;
    Toolbar toolbar;
    Button mDoneView;
    Button mPreviewView;
    TextView title;

    private ImageFolderPopupWindow mFolderPopupWindow;
    private ImageFolderAdapter mImageFolderAdapter;
    private ImageAdapter mImageAdapter;

    private List<Image> mSelectedImage;

    private String mCamImageName;
    private LoaderListener mCursorLoader = new LoaderListener();

    private SelectImageContract.Operator mOperator;
    private MediaStoreDataFactory mFactory;


    @Override
    public void onAttach(Context context) {
        this.mOperator = (SelectImageContract.Operator) context;
        super.onAttach(context);
    }


    @Override
    protected int getContentViewId() {
        return R.layout.fragment_select_image;
    }

    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.back) {
            finish();

        } else if (i == R.id.btn_preview) {
            if (mSelectedImage.size() > 0) {
                ImageGalleryActivity.show(getActivity(), Util.getPath(mSelectedImage), 0, false);
            }

        } else if (i == R.id.title) {
            showPopupFolderList();

        } else if (i == R.id.btn_done) {
            handleResult();

        }
    }

    @Override
    public void initView(View view) {
//        icon_bottom = ContextCompat.getDrawable(getContext(),R.drawable.icon_down);
//        icon_top = ContextCompat.getDrawable(getContext(),R.drawable.icon_up);
        mContentView = (RecyclerView) view.findViewById(R.id.rv_image);
        toolbar = (Toolbar)view.findViewById(R.id.toolbar);
        toolbar.setNavigationIcon(R.drawable.icon_back_f);

        title = (TextView)view.findViewById(R.id.title);
        title.setOnClickListener(this);

        mDoneView = (Button) view.findViewById(R.id.btn_done);
        mDoneView.setOnClickListener(this);
        mPreviewView = (Button) view.findViewById(R.id.btn_preview);
        mPreviewView.setOnClickListener(this);

        mContentView.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        mContentView.addItemDecoration(new SpaceGridItemDecoration((int) Ui.dipToPx(getResources(), 1)));
        mImageAdapter = new ImageAdapter(getContext(), this);
        mImageFolderAdapter = new ImageFolderAdapter(getActivity());
        mImageFolderAdapter.setLoader(this);
        mContentView.setAdapter(mImageAdapter);
        mContentView.setItemAnimator(null);
        mImageAdapter.setOnItemClickListener(this);
        SelectImageActivity.Config config = mOperator.getConfig();
        if(config.getSelectCount()==1){
            view.findViewById(R.id.lay_button).setVisibility(View.GONE);
        }
        mImageAdapter.setSelectCount(config.getSelectCount());

    }

    @Override
    protected void onResumeView() {
        super.onResumeView();
        ((BaseActivity) getActivity()).setSupportActionBar(toolbar);
        ((BaseActivity) getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
    }

    @Override
    protected void initData() {
        mSelectedImage = new ArrayList<>();
        SelectImageActivity.Config config = mOperator.getConfig();
        if (config.getSelectCount() > 1 && config.getSelectedImages() != null) {
            String[] images = config.getSelectedImages();
            for (String s : images) {
                // check file exists
                if (s != null && new File(s).exists()) {
                    Image image = new Image();
                    image.setSelect(true);
                    image.setPath(s);
                    mSelectedImage.add(image);
                }
            }
        }
        getLoaderManager().initLoader(0, null, mCursorLoader);

        mFactory = new MediaStoreDataFactory(getContext(),this,this);
        getLoaderManager().initLoader(1, null, mFactory);
    }


    @Override
    public void onItemClick(int position, long itemId) {
        SelectImageActivity.Config config = mOperator.getConfig();
        if (config.isHaveCamera()) {
            if (position != 0) {
                handleSelectChange(position);
            } else {
                if (mSelectedImage.size() < config.getSelectCount()) {
                    toOpenCamera();
                } else {
                    Toast.makeText(getActivity(), "最多只能选择 " + config.getSelectCount() + " 张图片", Toast.LENGTH_SHORT).show();
                }
            }
        } else {
            handleSelectChange(position);
        }
    }

    private void handleSelectSizeChange(int size) {
        if (size > 0) {
            mPreviewView.setEnabled(true);
            mDoneView.setEnabled(true);
            mDoneView.setText(String.format("%s(%s)", getText(R.string.image_select_opt_done), size));
        } else {
            mPreviewView.setEnabled(false);
            mDoneView.setEnabled(false);
            mDoneView.setText(getText(R.string.image_select_opt_done));
        }
    }

    private void handleSelectChange(int position) {
        Image image = mImageAdapter.getItem(position);
        SelectImageActivity.Config config = mOperator.getConfig();
        //如果是多选模式
        final int selectCount = config.getSelectCount();
        if (selectCount > 1) {
            if (image.isSelect()) {
                image.setSelect(false);
                mSelectedImage.remove(image);
                mImageAdapter.updateItem(position);
            } else {
                if (mSelectedImage.size() == selectCount) {
                    Toast.makeText(getActivity(), "最多只能选择 " + selectCount + " 张照片", Toast.LENGTH_SHORT).show();
                } else {
                    image.setSelect(true);
                    mSelectedImage.add(image);
                    mImageAdapter.updateItem(position);
                }
            }
            handleSelectSizeChange(mSelectedImage.size());
        } else {
            mSelectedImage.clear();
            mSelectedImage.add(image);
            handleResult();
        }
    }

    private void handleResult() {
        if (mOperator != null && mSelectedImage.size() != 0) {
            if(mOperator.getConfig().isNeedClip()){
                mOperator.showClip(mSelectedImage.get(0).getPath());
            }else if(mOperator.getConfig().isNeedCompress()){
                List<String> paths = new ArrayList();
                for(Image image:mSelectedImage){
                    Bitmap bitmap = Util.compress(image.getPath());
                    if(bitmap==null) {
                        continue;
                    }
                    DiskCache.putBitmap(image.getName(), bitmap);
                    paths.add(DiskCache.getFilePath(image.getName()));
                }
                mOperator.getCallback().doSelectDone(Util.getPath(mSelectedImage),Util.toArray(paths));
                getActivity().finish();
            }else{
                mOperator.getCallback().doSelectDone(Util.getPath(mSelectedImage),null);
                getActivity().finish();
            }
        }else{
            getActivity().finish();
        }
    }

    public void onKeyBack(){
        handleResult();
    }

    /**
     * 创建弹出的相册
     */
    private void showPopupFolderList() {
        if (mFolderPopupWindow == null) {
            ImageFolderPopupWindow popupWindow = new ImageFolderPopupWindow(getActivity(), new ImageFolderPopupWindow.Callback() {
                @Override
                public void onSelect(ImageFolderPopupWindow popupWindow, ImageFolder model) {
                    mFactory.selectFolder(model);

                    addImagesToAdapter(model.getImages());
                    mContentView.scrollToPosition(0);
                    popupWindow.dismiss();
//                    toolbar.setTitle(annoModel.getName());
                    title.setText(model.getName());
                }

                @Override
                public void onDismiss() {
//                    title.setCompoundDrawables(null, null, icon_bottom, null);
                    title.setSelected(false);
                }

                @Override
                public void onShow() {
//                    title.setCompoundDrawables(null, null, icon_top, null);
                    title.setSelected(true);
                }
            });
            popupWindow.setAdapter(mImageFolderAdapter);
            mFolderPopupWindow = popupWindow;
        }
        mFolderPopupWindow.showAsDropDown(toolbar);
    }

    /**
     * 打开相机
     */
    private void toOpenCamera() {
        // 判断是否挂载了SD卡
        mCamImageName = null;
        String savePath = "";
        if (Util.hasSDCard()) {
            savePath = Util.getCameraPath();
            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdirs();
            }
        }

        // 没有挂载SD卡，无法保存文件
        if (TextUtils.isEmpty(savePath)) {
            Toast.makeText(getActivity(), "无法保存照片，请检查SD卡是否挂载", Toast.LENGTH_LONG).show();
            return;
        }

        mCamImageName = Util.getSaveImageFullName();
        File out = new File(savePath, mCamImageName);
        Uri uri = Uri.fromFile(out);

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent,
                0x03);
    }

    /**
     * 拍照完成通知系统添加照片
     *
     * @param requestCode requestCode
     * @param resultCode  resultCode
     * @param data        data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == BaseActivity.RESULT_OK && requestCode == 0x03 && mCamImageName != null) {
            Uri localUri = Uri.fromFile(new File(Util.getCameraPath() + mCamImageName));
            Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
            getActivity().sendBroadcast(localIntent);
        }
    }

    @Override
    public void displayImage(android.widget.ImageView iv, String path) {
        RequestBuilder<Drawable> apply = getGlide()
                .load(path)
                .load(path)
                .apply(new RequestOptions()
                        .centerCrop()
                        .placeholder(R.color.grey_200)
                        .error(R.drawable.ic_default_image_error)
                );
        if(path.toLowerCase().endsWith("gif")){
            apply=apply.apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.RESOURCE));
        }
        apply.into(iv);

        /*DrawableRequestBuilder builder = getGlide().load(path)
                .centerCrop()
                .placeholder(R.color.grey_200)
                .error(R.drawable.ic_default_image_error);
        if (path.toLowerCase().endsWith("gif"))
            builder = builder.diskCacheStrategy(DiskCacheStrategy.SOURCE);
        builder.into(iv);*/
    }

    @Override
    public void onFolderRemoved(List<ImageFolder> images) {
        Log.e("TAG", "onFolderRemoved: "+images.size());
    }

    @Override
    public void onFolderAdded(List<ImageFolder> images) {
        Log.e("TAG", "onFolderAdded: "+images.size());
    }

    @Override
    public void onFolderUpdated(List<ImageFolder> images) {
        Log.e("TAG", "onFolderUpdated: "+images.size());
    }

    @Override
    public void onPictureRemoved(List<Image> images) {
        Log.e("TAG", "onPictureRemoved: "+images.size());
    }

    @Override
    public void onPictureAdded(List<Image> images) {
        Log.e("TAG", "onPictureAdded: "+images.size());
    }

    private class LoaderListener implements LoaderManager.LoaderCallbacks<Cursor> {
        private final String[] IMAGE_PROJECTION = {
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Media._ID,
                MediaStore.Images.Media.MINI_THUMB_MAGIC,
                MediaStore.Images.Media.BUCKET_DISPLAY_NAME};

        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            if (id == 0) {
                //数据库光标加载器
                return new CursorLoader(getContext(),
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION,
                        null, null, IMAGE_PROJECTION[2] + " DESC");
            }
            return null;
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            if (data != null) {
                ArrayList<Image> images = new ArrayList<>();
                List<ImageFolder> imageFolders = new ArrayList<>();

                ImageFolder defaultFolder = new ImageFolder();
                defaultFolder.setName("全部照片");
                defaultFolder.setPath("");
                imageFolders.add(defaultFolder);

                int count = data.getCount();
                if (count > 0) {
                    data.moveToFirst();
                    do {
                        String path = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
                        String name = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[1]));
                        long dateTime = data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
                        int id = data.getInt(data.getColumnIndexOrThrow(IMAGE_PROJECTION[3]));
                        String thumbPath = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[4]));
                        String bucket = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[5]));

                        Image image = new Image();
                        image.setPath(path);
                        image.setName(name);
                        image.setDate(dateTime);
                        image.setId(id);
                        image.setThumbPath(thumbPath);
                        image.setFolderName(bucket);
                        images.add(image);

                        //如果是新拍的照片
                        if (mCamImageName != null && mCamImageName.equals(image.getName())) {
                            image.setSelect(true);
                            mSelectedImage.add(image);
                        }

                        //如果是被选中的图片
                        if (mSelectedImage.size() > 0) {
                            for (Image i : mSelectedImage) {
                                if (i.getPath().equals(image.getPath())) {
                                    image.setSelect(true);
                                }
                            }
                        }

                        File imageFile = new File(path);
                        File folderFile = imageFile.getParentFile();
                        ImageFolder folder = new ImageFolder();
                        folder.setName(folderFile.getName());
                        folder.setPath(folderFile.getAbsolutePath());
                        if (!imageFolders.contains(folder)) {
                            folder.getImages().add(image);
                            folder.setAlbumPath(image.getPath());//默认相册封面
                            imageFolders.add(folder);
                        } else {
                            // 更新
                            ImageFolder f = imageFolders.get(imageFolders.indexOf(folder));
                            f.getImages().add(image);
                        }


                    } while (data.moveToNext());
                }

                addImagesToAdapter(images);
                defaultFolder.getImages().addAll(images);
                if (mOperator.getConfig().isHaveCamera()) {
                    defaultFolder.setAlbumPath(images.size() > 1 ? images.get(1).getPath() : null);
                } else {
                    defaultFolder.setAlbumPath(images.size() > 0 ? images.get(0).getPath() : null);
                }
                mImageFolderAdapter.resetItem(imageFolders);

                //删除掉不存在的，在于用户选择了相片，又去相册删除
                if (mSelectedImage.size() > 0) {
                    List<Image> rs = new ArrayList<>();
                    for (Image i : mSelectedImage) {
                        File f = new File(i.getPath());
                        if (!f.exists()) {
                            rs.add(i);
                        }
                    }
                    mSelectedImage.removeAll(rs);
                }

                // If add new mCamera picture, and we only need one picture, we result it.
                if (mOperator.getConfig().getSelectCount() == 1 && mCamImageName != null) {
                    handleResult();
                }

                handleSelectSizeChange(mSelectedImage.size());
            }
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {

        }
    }

    private void addImagesToAdapter(ArrayList<Image> images) {
        mImageAdapter.clear();
        if (mOperator.getConfig().isHaveCamera()) {
            Image cam = new Image();
            mImageAdapter.addItem(cam);
        }
        mImageAdapter.addAll(images);
    }
}
